package com.yugao.fintech.draper.generate.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yugao.fintech.draper.datasource.entity.PageQuery;
import com.yugao.fintech.draper.generate.entity.DynamicColumn;
import com.yugao.fintech.draper.generate.entity.DynamicTable;
import com.yugao.fintech.draper.generate.mapper.DynamicTableMapper;
import com.yugao.fintech.draper.generate.service.DynamicTableService;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class DynamicTableServiceImpl implements DynamicTableService {

	private final DynamicTableMapper dynamicTableMapper;

	/**
	 * 获取表基本信息
	 */
	@DS("#last")
	@Override
	public DynamicTable findByTableName(String tableName, String dsName) {
		return dynamicTableMapper.findByTableName(tableName);
	}

	/**
	 * 获取表的列信息
	 */
	@DS("#last")
	@Override
	public List<DynamicColumn> findColumnByTableName(String tableName, String dsName) {
		return dynamicTableMapper.findColumnByTableName(tableName);
	}

	/**
	 * 分页查询基础表信息
	 * @param pageParam 分页参数
	 * @param param 查询参数
	 * @return 分页信息
	 */
	@DS("#last")
	public IPage<DynamicTable> page(PageQuery pageParam, DynamicTable param) {
		Page<DynamicTable> page = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());
		// 实体类entity及其字段没有缓存或者说指定字段没有缓存
		// https://blog.csdn.net/qq_36491545/article/details/109091325
		TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
				DynamicTable.class);
		return dynamicTableMapper.page(page, Wrappers.<DynamicTable>lambdaQuery()
			.like(StringUtils.isNotEmpty(param.getTableName()), DynamicTable::getTableName, param.getTableName()));
	}
}
